package org.ghost.spring.cloud.consumer.demo.common.json.deserialize;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import org.ghost.spring.cloud.consumer.demo.util.DateUtil;
import org.ghost.spring.cloud.consumer.demo.util.NumberUtil;

import java.io.IOException;
import java.util.Date;

public class DateDeserializer extends JsonDeserializer<Date> {
    private final String SPACE_STRING = " ";

    @Override
    public Date deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        JsonToken currentToken = p.getCurrentToken();
        if (currentToken == JsonToken.VALUE_NUMBER_INT) {
            return new Date(Long.parseLong(p.getText()));
        } else if (currentToken == JsonToken.VALUE_STRING) {
            String text = p.getText().trim();
            long longVal = NumberUtil.toLong(text, -1);
            if (longVal > 0) {
                return new Date(longVal);
            } else {
                if (text.contains(SPACE_STRING)) {
                    return DateUtil.strToDateYMD_HMS(text);
                } else {
                    return DateUtil.strToDateYMD(text);
                }
            }
        } else if (currentToken == JsonToken.START_OBJECT) {
            JsonToken jsonToken = p.nextToken();
            if (jsonToken == JsonToken.FIELD_NAME) {
                p.nextToken();
                String text = p.getText().trim();
                p.nextToken();
                return DateUtil.strToDateYMD_HMS(text);
            }
        }
        return null;
    }
}
